package com.boot.readFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.nacos.common.utils.StringUtils;
import com.boot.common.utils.AliyunOSSUtil;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;
import org.apache.pdfbox.util.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ReadPDFUtils {

    @Autowired
    AliyunOSSUtil aliyunOSSUtil;

    /**
     * 提取PDF文件中的文本内容
     *
     * @param file         文件路径
     * @param targerFolder 照片存放文件夹路径
     * @throws IOException
     */
    public List<Map<String, Object>> readFileOfPDF(File file, String targerFolder) {
        List<Map<String, Object>> list = new ArrayList<>();
        String context = null;
        FileInputStream infile = null;
        List<String> urlList = this.extractImages(file, targerFolder);
        try {
            infile = new FileInputStream(file);// 创建一个文件输入流
            // 新建一个PDF解析器对象
            PDFParser parser = new PDFParser(new RandomAccessBufferedFileInputStream(file));
            // 对PDF文件进行解析
            parser.parse();
            // 获取解析后得到的PDF文档对象
            PDDocument pdfdocument = parser.getPDDocument();
            // 获取页码
            int pages = pdfdocument.getNumberOfPages();
            // 新建一个PDF文本剥离器
            PDFTextStripper stripper = new PDFTextStripper();
            for (int i = 1; i <= pages; i++) {
                Map<String, Object> m = new HashMap<>();
                // 从PDF文档对象中剥离文本
                stripper.setSortByPosition(true);
                stripper.setStartPage(i);
                stripper.setEndPage(i);
                context = stripper.getText(pdfdocument);
                // 如果文本内容不为空 则获取数据
                if (StringUtils.isNotBlank(context)) {

                    m.put("imgList", urlList.get(i - 1));
                    list.add(m);
                } else {// 如果为空则
                    list.get(list.size() - 1).put("imgList",
                            list.get(list.size() - 1).get("imgList").toString() + urlList.get(i - 1));
                }

            }

            return list;
        } catch (Exception e) {

            e.getMessage();

        } finally {

            if (infile != null) {
                try {
                    infile.close();
                } catch (IOException e1) {
                }
            }
        }
        return list;

    }

    public static void word(File file) throws Exception {
        PDDocument doc = null;
        try {
            doc = PDDocument.load(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int pagenumber = doc.getNumberOfPages();// 获取总页数
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("C:/Users/Administrator/Desktop/1.doc");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        PDFTextStripper stripper = null;
        try {
            stripper = new PDFTextStripper();
        } catch (IOException e) {
            e.printStackTrace();
        }
        stripper.setSortByPosition(true);// 排序
        stripper.setStartPage(1);// 设置转换的开始页
        stripper.setEndPage(pagenumber);// 设置转换的结束页
        try {
            stripper.writeText(doc, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.close();
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 提取PDF文件中的图片
     *
     * @param file         PDF文件
     * @param targetFolder 图片存放目录
     * @return
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public List<String> extractImages(File file, String targetFolder) {
        // 按页码返回照片集合
        List<String> list = new ArrayList<String>();
        try {
            PDDocument document = PDDocument.load(file);
            // 获取页数
            List<PDPage> pages = document.getDocumentCatalog().getAllPages();
            @SuppressWarnings("unused")
            Iterator<PDPage> iter = pages.iterator();
            for (int i = 0; i < pages.size(); i++) {
                String urls = "";
                PDPage page = pages.get(i);
                PDResources resources = page.getResources();
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setSortByPosition(true);
                stripper.setStartPage(i + 1);
                stripper.setEndPage(i + 1);
                // 获取图片
                Map<String, PDXObjectImage> images = resources.getImages();
                if (images != null) {
                    Iterator<String> imageIter = images.keySet().iterator();
                    int count = 0;
                    while (imageIter.hasNext()) {
                        count++;
                        String key = (String) imageIter.next();
                        if (!(key.equals("Im1") && StringUtils.isNotBlank(stripper.getText(document)))) {
                            PDXObjectImage image = (PDXObjectImage) images.get(key);
                            String name = file.getName() + "_" + count + ".png"; // 图片文件名
                            if (StringUtils.isNotBlank(targetFolder)) {
                                image.write2file(targetFolder + "\\" + name); // 保存图片
                            }
                            BufferedImage rgbImage = image.getRGBImage();
                            // 将照片上传至oss，拿到url
                            urls += aliyunOSSUtil.PDFImageUplod(rgbImage, name) + "urls";
                        }

                    }
                }
                list.add(urls);

            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return list;
    }

    /* ----------------------- pdfbox 2.0版本获取图片 start --------------- */
//    public static List<RenderedImage> getImagesFromPDF(PDDocument document) throws IOException {
//        List<RenderedImage> images = new ArrayList<RenderedImage>();
//        for (PDPage page : document.getPages()) {
//            images.addAll(getImagesFromResources(page.getResources()));
//        }
//
//        return images;
//    }
//    private static List<RenderedImage> getImagesFromResources(PDResources resources) throws IOException {
//        List<RenderedImage> images = new ArrayList<RenderedImage>();
//
//        for (COSName xObjectName : resources.getXObjectNames()) {
//            PDXObject xObject = resources.getXObject(xObjectName);
//
//            if (xObject instanceof PDFormXObject) {
//                continue;
//                //images.addAll(getImagesFromResources(((PDFormXObject) xObject).getResources()));
//            } else if (xObject instanceof PDImageXObject) {
//                PDImageXObject obj = (PDImageXObject) xObject;
//                //获取图片后缀
//                System.out.println(obj.getSuffix());
//                images.add(obj.getImage());
//            }
//        }
//
//        return images;
//    }
    /* --------------------pdfbox 2.0版本获取图片 end------------------------ */

    static String PDFPath = "C:/Users/86150/Desktop/成长档案pdf"; // 文件路径
    static String targerFolder = "C:/Users/86150/Desktop/pdf"; // 图片保存地址

//     public static void main(String[] args) throws Exception {
//     File file = new File(PDFPath);// File类型可以是文件也可以是文件夹
//     File[] fileList = file.listFiles();// 将该目录下的所有文件放置在一个File类型的数组中
//     // word(file);
//     for (File f : fileList) {
//     System.out.println(f);
//     readFileOfPDF(f, targerFolder);
//     }
//
//     }

}

